// pages/order/notarize/notarize.js
var app = getApp();
var getImgarr = []; //需要过度展示图片
var upimgarr = []; //上传七牛云成功后返给后台的图片
var uping = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    noteMaxLen: 200,
    currentNoteLen: 0,
    imgUrl: [], //选择的照片
    upchoosebox: [], //上传的照片
    valcontent: '', //内容
    firstClick: true, //第一次点击提交
    armaStorList: [], //配件使用
    basicsStorlist: [], //基础服务
    filterelementList: [], //滤芯服务
    serviceList: [], //服务列表
    allMoney: 0, //总金额
    changemoney: 0, //修改后的金额
    nums: 0, //总数量
    checked: 1, //支付方式
    armaVl: 0, //配件
    basicsVl: 0, //基础
    filtereVl: 0, //滤芯
    serviceVl: 0, //额外
    work_order_id: '',
    disabled: false, //开关
    return_water_serverMoney: '',//首年改造服务费
    next_year_payment_amount: '',//次年改造服务费
    return_trueNum: '',
    cash_pay: false,//是否支持现金收款
    transfer_pay: false,//是否支持对公转账
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    if (options.work_order_id != undefined) {
      that.setData({
        work_order_id: options.work_order_id,
        // return_water_serverMoney: options.serverMoney,
        // next_year_payment_amount: options.serverMoney2,
        // return_trueNum: options.trueNum
      })
    } else {
      app.showToast("工单号为空请重试", "none", 2000, function() {});
    }
    getImgarr = [];
    upimgarr = [];
    that.getCashConfig();
    that.getTransferConfig();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    getImgarr = [];
    upimgarr = [];
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    var getMoney = 0;
    var nums = 0;
    var avlue = 0,
      bvlue = 0,
      cvlue = 0,
      dvlue = 0;
    var armaStor = wx.getStorageSync('armature') ? JSON.parse(wx.getStorageSync('armature')) : [];
    var basicsStor = wx.getStorageSync('basics') ? JSON.parse(wx.getStorageSync('basics')) : [];
    var filterelement = wx.getStorageSync('filterelement') ? JSON.parse(wx.getStorageSync('filterelement')) : [];
    var service = wx.getStorageSync('service') ? JSON.parse(wx.getStorageSync('service')) : [];
    var valcontent = wx.getStorageSync('valcontent') ? wx.getStorageSync('valcontent') : '暂无备注';
    var showImg = wx.getStorageSync('showImg') ? JSON.parse(wx.getStorageSync('showImg')) : [];
    var upImg = wx.getStorageSync('upImg') ? JSON.parse(wx.getStorageSync('upImg')) : [];
    var needCharge = wx.getStorageSync('need_charge') ? wx.getStorageSync('need_charge') : '';
    // console.log('>><配件', armaStor);
    //console.log('>><基础', basicsStor);
    console.log('>><滤芯', filterelement);
    // console.log('>><额外', service);
    nums = parseInt(armaStor.length) + parseInt(basicsStor.length) + parseInt(filterelement.length) + parseInt(service.length);

    for (var a in basicsStor) {
      getMoney += parseInt(basicsStor[a].cost * basicsStor[a].goods_num) + parseInt(basicsStor[a].other_cost);
      avlue += parseInt(basicsStor[a].cost * basicsStor[a].goods_num) + parseInt(basicsStor[a].other_cost);
    }
    for (var b in filterelement) {
      getMoney += parseInt(filterelement[b].cost * filterelement[b].goods_num);
      bvlue += parseInt(filterelement[b].cost * filterelement[b].goods_num);
    }
    for (var c in armaStor) {
      getMoney += parseInt(armaStor[c].cost * armaStor[c].goods_num);
      cvlue += parseInt(armaStor[c].cost * armaStor[c].goods_num);
    }
    for (var d in service) {
      getMoney += parseInt(service[d].cost) * parseInt(service[d].goods_num);
      dvlue += parseInt(service[d].cost) * parseInt(service[d].goods_num);
    }
    //是否需要收机器的钱
    if (needCharge.is_collect_money == 1 && needCharge != '') {
      getMoney += parseInt(needCharge.money * 100)
    }

    // 是否修改过实付款
    var changemoney = wx.getStorageSync('changemoney');
    var allMoney = '';
    if (changemoney == '' || changemoney == undefined){
      changemoney = getMoney / 100;
      allMoney = getMoney / 100;
    }else{
      allMoney = changemoney;
    }
    that.setData({
      armaStorList: armaStor,
      basicsStorlist: basicsStor,
      filterelementList: filterelement,
      serviceList: service,
      allMoney: allMoney,
      changemoney: changemoney,
      nums: nums,
      valcontent: valcontent,
      imgUrl: showImg,
      upchoosebox: upImg,
      basicsVl: avlue / 100,
      filtereVl: bvlue / 100,
      serviceVl: dvlue / 100,
      armaVl: cvlue / 100,
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  //选中的结果
  checkboxChange(e) {
    var that = this;
    var vlueshow = e.currentTarget.dataset.vlueshow;
    that.setData({
      checked: vlueshow
    })
  },
  checkboxChangetwo(e) {
    var that = this;
    var vlueshow = e.currentTarget.dataset.vlueshow;
    that.setData({
      checked: vlueshow
    })
  },
  //实际支付
  chenginput(e) {
    var that = this;
    wx.setStorageSync('changemoney', e.detail.value);
    that.setData({
      changemoney: e.detail.value,
      allMoney: e.detail.value
    })
  },
  //提交表单
  upBackOrder: function() {
    var that = this;
    var work_order_id = that.data.work_order_id;
    var pay_client = that.data.checked;
    var content = that.data.valcontent;
    var upchoosebox = that.data.upchoosebox;
    var changemoney = that.data.changemoney;
    var parts = []; //配件
    var armaStorList = that.data.armaStorList; //配件
    var allMoney = that.data.allMoney; //总金额
    for (var m in armaStorList) {
      var obja = {};
      obja.id = armaStorList[m].parts_id;
      obja.num = armaStorList[m].goods_num;
      parts.push(obja);
    }
    //console.log('配件', parts)
    var base_service = []; //基础
    var basicsStorlist = that.data.basicsStorlist; //基础
    for (var n in basicsStorlist) {
      var objb = {};
      objb.id = basicsStorlist[n].business_type_id;
      objb.num = basicsStorlist[n].goods_num;
      base_service.push(objb);
    }
    //console.log('转换后基础', base_service);
    var filter_element = []; //滤芯
    var filterelementList = that.data.filterelementList; //滤芯
    for (var l in filterelementList) {
      var objc = {};
      objc.id = filterelementList[l].parts_id;
      objc.num = filterelementList[l].goods_num;
      objc.cycle = filterelementList[l].cycle;
      filter_element.push(objc);
    }
    console.log('转换后滤芯', filter_element);
    var add_service = []; //服务
    var serviceList = that.data.serviceList; //服务
    console.log('基础??', serviceList);
    for (var q in serviceList) {
      var objd = {};
      objd.id = serviceList[q].service_id;
      objd.num = serviceList[q].goods_num;
      add_service.push(objd);
    }
    console.log('转换后服务', add_service);
    app.ajax({
      url: 'Engineer/Workorder/receiptOrder',
      data: {
        work_order_id: work_order_id,
        receipt_content: content,
        receipt_pic: upchoosebox,
        pay_client: pay_client,
        total: changemoney,
        parts: parts,
        base_service: base_service,
        // filter_element: filter_element,
        add_service: add_service,
        // payment_amount: that.data.return_water_serverMoney,
        // next_year_payment_amount: that.data.next_year_payment_amount,
        // actual_transformation_num: that.data.return_trueNum,
        receipt_content: that.data.valcontent,
      },
      success: function(res) {
        // console.log('结果???', res)
        if (res.data.code == 1000) {
          if (allMoney == 0 || pay_client == 3 || pay_client == 4) {
            app.showToast("回单成功！2s后跳转列表");
            var timer = setTimeout(function() {
              wx.navigateBack({
                delta: 2
              })
            }, 2000)
          } else {
            if (pay_client == 2) {
              that.payment(); //调用自己支付
            } else {
              wx.navigateTo({
                url: '../receivables/receivables?work_order_id=' + res.data.data.work_order_id,
              })
              // wx.reLaunch({
              //   url: '../receivables/receivables?work_order_id=' + res.data.data.work_order_id,
              // })
            }
          }


          //app.showToast(res.data.message, "none", 2000, function () { });

        } else {
          app.showToast(res.data.message, "none", 2000, function() {});
        }
      }
    })
  },
  payment: function() {
    var that = this;
    that.setData({
      disabled: true
    })
    var work_order_id = that.data.work_order_id;
    app.ajax({
      url: 'Engineer/Pay/pay',
      method: "POST",
      data: {
        work_order_id: work_order_id,
      },
      success: function(res) {
        //console.log(res)
        if (res.data.code == 1000) {
          var jsapi = res.data.data.jsapi;
          wx.requestPayment({
            timeStamp: jsapi.timeStamp,
            nonceStr: jsapi.nonceStr,
            package: jsapi.package,
            signType: jsapi.signType,
            paySign: jsapi.paySign,
            'success': function(res) {
              that.setData({
                disabled: false
              })
              app.showToast("支付成功");
              wx.setStorageSync('tabIndex', 3);
              wx.removeStorageSync('basics'); //清除缓存
              wx.removeStorageSync('filterelement'); //清除缓存
              wx.removeStorageSync('service'); //清除缓存
              wx.removeStorageSync('valcontent'); //清除缓存
              wx.removeStorageSync('showImg'); //清除缓存
              wx.removeStorageSync('upImg'); //清除缓存  
              wx.removeStorageSync('armature'); //清除缓存
              wx.removeStorageSync('need_charge');
              wx.switchTab({
                url: '../myorder/myorder',
              })
            },
            'fail': function(res) {
              that.setData({
                disabled: false
              })
              app.showToast("支付失败");
              // console.log(res);
            }
          })
        } else {
          app.showToast(res.data.message);
        }

      }
    })
  },
  //获取是否现金收款
  getCashConfig() {
    var that = this;
    app.ajax({
      url: 'Common/Common/getSystemConfig',
      data: {
        key: 'enginer_cash_pay',
      },
      success: function (res) {
        console.log(res.data)
        if (res.data.code == 1000 && res.data.data == 1) {
          that.setData({
            cash_pay: true
          })
        }
      }
    })
  },

  // 图片放大预览
  previewImage(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.url,
      urls: this.data.imgUrl // 需要预览的图片http链接列表
    })
  },

 //获取是否对公转账
  getTransferConfig() {
    var that = this;
    var work_order_id = that.data.work_order_id;
    app.ajax({
      url: 'Engineer/Workorder/getUserClass',
      data: {
        work_order_id: work_order_id,
        key:'enginer_transfer_pay'
      },
      success: function (res) {
        
        if (res.data.code == 1000 && (res.data.data.user_class == 2 || res.data.data.user_class == 3) && res.data.data.key == 1) {//如果是企业用户并且后台开启对公转账
          that.setData({
            transfer_pay: true
          })
          
        }
      }
    })
  }

})